﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Jayden.Dll.Updater
{
	public class FileVersionInformation
	{
		private string m_RelativePath;
		private string m_FilePath;
		private byte[] m_FileHash;

		public FileVersionInformation(string filepath) : this(filepath, filepath) { }
		public FileVersionInformation(string filepath, string relativePath)
		{
			m_RelativePath = relativePath;
			m_FilePath = filepath;
			if (!string.IsNullOrWhiteSpace(filepath) && File.Exists(filepath))
			{
				using (FileStream stream = new FileStream(filepath, FileMode.Open))
				{
					using (SHA1Managed sha1 = new SHA1Managed())
					{
						m_FileHash = sha1.ComputeHash(stream);
					}
				}
			}
			else
				m_FileHash = new byte[20];
		}
		public FileVersionInformation(string filepath, string relativePath, byte[] hash)
		{
			m_FilePath = null;
			m_RelativePath = relativePath;
			m_FileHash = hash;
		}

		public string FilePath { get { return m_FilePath; } }
		public string RelativePath { get { return m_RelativePath; } }
		public byte[] FileHash { get { return m_FileHash; } }

		public override string ToString()
		{
			StringBuilder builder = new StringBuilder(2 * m_FileHash.Length);
			foreach (byte b in m_FileHash)
				builder.AppendFormat("{0:X2}", b);
			return builder.ToString();
		}

		public override bool Equals(object obj)
		{
			if (obj is FileVersionInformation)
			{
				FileVersionInformation file = obj as FileVersionInformation;
				if (file.RelativePath != RelativePath)
					return false;
				for (int c = 0; c < m_FileHash.Length; c++)
					if (m_FileHash[c] != file.m_FileHash[c])
						return false;
				return true;
			}
			return base.Equals(obj);
		}

		public override int GetHashCode() { return m_RelativePath.GetHashCode(); }
	}
}
